package com.pipe.protocol.events.table;

import com.pipe.protocol.events.table.reader.ColumnType;
import com.pipe.util.MyBytebufUtil;
import com.pipe.util.MysqlProtocolUtil;
import io.netty.buffer.ByteBuf;

import java.util.Arrays;

/**
 * @author Kiven
 */
public class TableMapEventPayLoad {
    private short schemaNameLength;
    private String schemaName;
    private short tableNameLength;
    private String tableName;

    private long columnCount;
    private ColumnType[] columnTypeDef;
    private byte[] columnMetaDef;
    private byte[] nullBitmap;

    public TableMapEventPayLoad(short schemaNameLength, String schemaName, short tableNameLength, String tableName, long columnCount,
                                ColumnType[] columnTypeDef, byte[] columnMetaDef, byte[] nullBitmap) {
        this.schemaNameLength = schemaNameLength;
        this.schemaName = schemaName;
        this.tableNameLength = tableNameLength;
        this.tableName = tableName;
        this.columnCount = columnCount;
        this.columnTypeDef = columnTypeDef;
        this.columnMetaDef = columnMetaDef;
        this.nullBitmap = nullBitmap;
    }

    public static TableMapEventPayLoad build(ByteBuf byteBuf){
        short snl = byteBuf.readUnsignedByte();
        String sn = MyBytebufUtil.readStringFromBytebuf(byteBuf, snl);

        byteBuf.readByte();//空读一位

        short tnl = byteBuf.readUnsignedByte();
        String tn = MyBytebufUtil.readStringFromBytebuf(byteBuf, tnl);

        byteBuf.readByte();//空读一位
        long cc = MysqlProtocolUtil.readLenencIntFromBytebuf(byteBuf);
        byte[] ctd = MyBytebufUtil.readByteFromBytebuf(byteBuf, (int) cc);
        ColumnType[] columnTypes = readColumnType(ctd);
        byte[] cmd = MysqlProtocolUtil.readLenencStringOfByteFromBytebuf(byteBuf);
        byte[] nb = MyBytebufUtil.readByteFromBytebuf(byteBuf, ((int)cc + 7) / 8 );

        return new TableMapEventPayLoad(snl, sn, tnl, tn, cc, columnTypes, cmd, nb);
    }

    private static ColumnType[] readColumnType(byte[] ctd){
        ColumnType[] columnTypes = new ColumnType[ctd.length];
        for (int i=0; i<ctd.length; i++) {
            columnTypes[i] = ColumnType.getColumnType(ctd[i]);
        }
        return columnTypes;
    }

    public ColumnType[] getColumnTypeDef() {
        return columnTypeDef;
    }

    public String getTableName() {
        return tableName;
    }

    @Override
    public String toString() {
        return "TableMapEventPayLoad{" +
                "schemaNameLength=" + schemaNameLength +
                ", schemaName='" + schemaName + '\'' +
                ", tableNameLength=" + tableNameLength +
                ", tableName='" + tableName + '\'' +
                ", columnCount=" + columnCount +
                ", columnTypeDef=" + Arrays.toString(columnTypeDef) +
                ", columnMetaDef=" + Arrays.toString(columnMetaDef) +
                ", nullBitmap=" + Arrays.toString(nullBitmap) +
                '}';
    }
}